<?php

namespace App\Http\Controllers\Api;


use App\Modules\User\Manager;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class AuthController extends ApiController
{
    protected $url;
    protected $generator;

    //TODO test
    public function test()
    {
        $app = EasyWeChat::officialAccount();
        $redirectUrl = $app->oauth->redirect();
        return $redirectUrl;
    }

    public function test1()
    {
        $app = EasyWeChat::officialAccount();
        $user = $app->oauth->user();
        $app->template_message->send([
            'touser' => $user->getId(),
            'template_id' => 'yjVgpuEKq6fsUqjk_N1LrkCUnYTeg0aUPr3uV8LRTio',
            'url' => 'https://www.baidu.com',//跳转链接
//            'miniprogram' => [  //跳转小程序
//                'appid' => 'wx3304682b95b21a04',
//                'pagepath' => 'pages/index',
//            ],
            'data' => [
                'first' => '您好，您已成功注册',
                'keyword1' => 'test',
                'keyword2' => '12314',
                'remark' => '感谢您的注册，有疑问请联系客服！',
            ],
        ]);
        dd($user);
    }

    public function login(Request $request)
    {
        if (Auth::guard('api')->check()) {
            return $this->success();
        }

        $code = $request->input('code');

        if (is_null($code)) {
            return $this->fail('Need auth', 1001);
        }

        $app = EasyWeChat::miniProgram();
        $data = $app->auth->session($code);

        $user = Manager::getUserByOpenid($data['openid']);
        if (!isset($data['unionid']) || empty($data['unionid'])) {
            Log::error($data);
        }
//        $data['unionid'] = "unionid1234567890";
        if (is_null($user)) {
            $user = Manager::registerWeChat($data['unionid'], [
                'sessionKey' => $data['session_key'],
                'openid' => $data['openid'],
            ]);
        } else {
            $user->session_key = $data['session_key'];
            if (empty($user->unionid)) {
                $user->unionid = $data['unionid'];
            }
            $user->save();
        }
        $token = auth('api')->fromUser($user);
        auth('api')->setToken($token)->setUser($user);

        return $this->success([
            'token' => $token,
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }


    protected function officialAccountLogin(Request $request)
    {
        if (Auth::guard('api')->check()) {
            return $this->success();
        }
        $code = $request->input('code');
        $result = parse_url(url()->previous());
        $url = "{$result['scheme']}://{$result['host']}{$result['path']}?" . http_build_query($request->except('code'));
        if (is_null($code)) {
            return $this->redirectAuth($url);
        }
        $app = EasyWeChat::officialAccount();
        $oauth = $app->oauth;
        $oauth->setRequest($request);
        $token = $oauth->getAccessToken($code);
        $weChatUser = $oauth->user($token);

        if (empty($weChatUser->getNickname())) {
            return $this->redirectAuth($url, 'snsapi_userinfo');
        }

        $data = $weChatUser->getOriginal();

        $user = Manager::registerWeChat($data['unionid'], [
            'nickname' => $weChatUser->getNickname(),
            'avatar' => $weChatUser->getAvatar(),
            'official_account_openid' => $weChatUser->getId(),
        ]);

        $token = auth('api')->fromUser($user);
        auth('api')->setToken($token)->setUser($user);

        return $this->success([
            'token' => $token,
            'expires_in' => auth('api')->factory()->getTTL(),
        ]);
    }

    private function redirectAuth($url, $scopes = 'snsapi_base')
    {
        /**
         * @var \Overtrue\Socialite\Providers\WeChatProvider $oauth
         */

        $oauth = EasyWeChat::officialAccount()->oauth;
        $response = $oauth->scopes([$scopes])->setRedirectUrl($url)->redirect();
        $oauthUrl = $response->getTargetUrl();
        return $this->fail('OAuth needed', 1, [
            'redirectUrl' => $oauthUrl,
        ]);
    }
}
